// 经纪人详情页脚本
document.addEventListener('DOMContentLoaded', function() {
    // 获取URL中的agent-id参数
    const urlParams = new URLSearchParams(window.location.search);
    const agentId = urlParams.get('id');
    
    // 如果没有agentId，显示错误信息
    if (!agentId) {
        showError('未找到经纪人信息');
        return;
    }
    
    // 加载经纪人详情
    loadAgentDetail(agentId);
    
    // 初始化返回按钮
    initBackButton();
    
    // 初始化分享按钮
    initShareButton();
    
    // 修改底部CTA样式
    updateBottomCTAStyle();
    
    // 监听窗口大小变化
    window.addEventListener('resize', function() {
        updateBottomCTAStyle();
    });
});

// 加载经纪人详情
function loadAgentDetail(agentId) {
    // 在真实应用中，这里应该从服务器获取数据
    // 这里我们使用模拟数据
    const agentData = getAgentData(agentId);
    
    // 如果找不到对应的经纪人数据，显示错误
    if (!agentData) {
        showError('未找到该经纪人信息');
        return;
    }
    
    // 渲染经纪人详情
    renderAgentDetail(agentData);
    
    // 更新底部价格
    updatePrice(agentData.minPrice);
    
    // 默认选中最低价位的服务
    selectMinPriceService(agentData);
    
    // 初始化页面交互
    initPageInteractions(agentData);
}

// 获取经纪人数据（模拟数据）
function getAgentData(agentId) {
    // 模拟的经纪人数据
    const agentsData = {
        'agent1': {
            id: 'agent1',
            name: '张明',
            title: '前BAT高级HR',
            avatar: 'https://images.pexels.com/photos/3760263/pexels-photo-3760263.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1',
            rating: 4.9,
            reviewCount: 243,
            level: '金牌',
            minPrice: 299,
            tags: ['简历优化', '面试辅导', '互联网行业'],
            about: '8年互联网HR经验，曾在BAT担任招聘负责人，擅长简历优化和面试指导，帮助200+学生成功入职一线互联网公司。对互联网企业招聘流程和筛选标准有深刻理解，能针对性辅导面试技巧。',
            stats: {
                students: '200+',
                satisfactionRate: '98%',
                salaryIncrease: '30%'
            },
            services: [
                {
                    name: '简历优化',
                    price: 299
                },
                {
                    name: '面试辅导',
                    price: 499
                },
                {
                    name: '全程跟踪',
                    price: 1999
                }
            ],
            experience: [
                {
                    title: '字节跳动',
                    position: '人才招聘高级经理',
                    period: '2018 - 2022',
                    description: '负责研发、产品、运营等岗位的校招与社招，建立人才评估体系'
                },
                {
                    title: '腾讯',
                    position: '招聘专员',
                    period: '2015 - 2018',
                    description: '负责技术岗位的人才招聘和评估工作'
                },
                {
                    title: '北京大学',
                    position: '人力资源管理专业',
                    period: '2011 - 2015',
                    description: '本科学历，人力资源管理专业'
                }
            ],
            reviews: [
                {
                    name: '李同学',
                    avatar: 'https://images.pexels.com/photos/1222271/pexels-photo-1222271.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1',
                    rating: 5,
                    date: '2023-03-15',
                    content: '张老师的简历指导非常专业，帮我重新梳理了项目经历，突出了核心能力。修改后的简历投递通过率提高了50%以上，最终收到了字节跳动的offer！'
                },
                {
                    name: '王同学',
                    avatar: 'https://images.pexels.com/photos/733872/pexels-photo-733872.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1',
                    rating: 5,
                    date: '2023-02-20',
                    content: '面试模拟非常有帮助，张老师提前帮我准备了可能遇到的各种问题，还针对我的回答给了很多中肯的建议。最终顺利通过了阿里的三轮面试，感谢张老师！'
                },
                {
                    name: '陈同学',
                    avatar: 'https://images.pexels.com/photos/1681010/pexels-photo-1681010.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1',
                    rating: 4,
                    date: '2023-01-10',
                    content: '全程跟踪服务非常贴心，从简历优化到面试准备再到offer选择，张老师都给了很多专业建议。唯一的小遗憾是有时回复不够及时，但总体来说非常满意。'
                }
            ]
        },
        'agent2': {
            id: 'agent2',
            name: '王静',
            title: '资深金融顾问',
            avatar: 'https://images.pexels.com/photos/5393594/pexels-photo-5393594.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1',
            rating: 5.0,
            reviewCount: 156,
            level: '金牌',
            minPrice: 399,
            tags: ['职业规划', '投行求职', '金融行业'],
            about: '毕业于哈佛商学院，曾在高盛工作10年，擅长投行求职指导和职业规划，帮助150+学生成功入职国内外顶级金融机构。熟悉金融行业各细分领域的要求和职业发展路径，能提供针对性的发展建议。',
            stats: {
                students: '150+',
                satisfactionRate: '100%',
                salaryIncrease: '45%'
            },
            services: [
                {
                    name: '求职规划',
                    price: 399
                },
                {
                    name: '案例分析',
                    price: 599
                },
                {
                    name: '全程辅导',
                    price: 2999
                }
            ],
            experience: [
                {
                    title: '高盛投资银行',
                    position: '副总裁',
                    period: '2012 - 2022',
                    description: '负责多个大型并购和IPO项目，管理投行分析师团队'
                },
                {
                    title: '摩根士丹利',
                    position: '分析师',
                    period: '2010 - 2012',
                    description: '参与企业融资和并购项目'
                },
                {
                    title: '哈佛商学院',
                    position: 'MBA',
                    period: '2008 - 2010',
                    description: '主修金融与战略管理'
                }
            ],
            reviews: [
                {
                    name: '刘同学',
                    avatar: 'https://images.pexels.com/photos/1043471/pexels-photo-1043471.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1',
                    rating: 5,
                    date: '2023-03-20',
                    content: '王老师的金融行业分析非常深入，帮我理清了不同细分领域的特点和要求，最终帮助我找到了最适合自己的方向。在她的指导下，我顺利拿到了高盛的offer！'
                },
                {
                    name: '张同学',
                    avatar: 'https://images.pexels.com/photos/937481/pexels-photo-937481.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1',
                    rating: 5,
                    date: '2023-02-15',
                    content: '案例分析课非常有价值，王老师分享了很多真实的投行案例和解题思路，让我在后续面试中表现得非常出色。强烈推荐给想进入金融行业的同学！'
                }
            ]
        },
        'agent3': {
            id: 'agent3',
            name: '李华',
            title: '金融行业导师',
            avatar: 'https://images.pexels.com/photos/3785104/pexels-photo-3785104.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1',
            rating: 4.8,
            reviewCount: 120,
            level: '银牌',
            minPrice: 199,
            tags: ['职业规划', '求职策略', '金融行业'],
            about: '曾在四大会计师事务所工作6年，现任某大型券商高管，擅长金融行业求职指导和职业发展规划。对会计、审计、证券等金融细分领域有丰富经验，能为学生提供实用的行业见解和求职技巧。',
            stats: {
                students: '120+',
                satisfactionRate: '95%',
                salaryIncrease: '25%'
            },
            services: [
                {
                    name: '职业规划',
                    price: 199
                },
                {
                    name: '简历优化',
                    price: 299
                },
                {
                    name: '求职辅导',
                    price: 1599
                }
            ],
            experience: [
                {
                    title: '某大型券商',
                    position: '投资总监',
                    period: '2018 - 至今',
                    description: '负责投资策略制定和团队管理'
                },
                {
                    title: '普华永道',
                    position: '高级审计师',
                    period: '2012 - 2018',
                    description: '负责金融机构审计工作'
                },
                {
                    title: '上海财经大学',
                    position: '金融学专业',
                    period: '2008 - 2012',
                    description: '本科学历，金融学专业'
                }
            ],
            reviews: [
                {
                    name: '赵同学',
                    avatar: 'https://images.pexels.com/photos/2379005/pexels-photo-2379005.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1',
                    rating: 5,
                    date: '2023-03-10',
                    content: '李老师的职业规划课程让我对金融行业有了更清晰的认识，找到了适合自己的发展方向。简历修改也非常专业，投递成功率大大提高。'
                },
                {
                    name: '孙同学',
                    avatar: 'https://images.pexels.com/photos/1516680/pexels-photo-1516680.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1',
                    rating: 4,
                    date: '2023-01-25',
                    content: '求职辅导很有针对性，李老师分享了很多行业内部的见解和面试技巧。唯一的建议是希望能增加更多实践性的内容，但总体来说非常满意。'
                }
            ]
        }
    };
    
    return agentsData[agentId];
}

// 渲染经纪人详情
function renderAgentDetail(data) {
    const detailContainer = document.getElementById('agent-detail-content');
    
    // 清空加载指示器
    detailContainer.innerHTML = '';
    
    // 创建页面内容
    let content = `
        <!-- 经纪人资料卡 -->
        <section class="agent-profile">
            <div class="profile-header">
                <img src="${data.avatar}" alt="${data.name}" class="profile-avatar">
                <div class="profile-badge">
                    <i class="bi bi-patch-check-fill"></i>
                </div>
                <div class="profile-info">
                    <h1 class="profile-name">${data.name}</h1>
                    <p class="profile-title">${data.title}</p>
                    <div class="profile-rating">
                        <div class="rating-stars">
                            <i class="bi bi-star-fill"></i>
                        </div>
                        <span class="rating-number">${data.rating}</span>
                        <span class="rating-count">${data.reviewCount}条评价</span>
                    </div>
                </div>
            </div>
            <div class="profile-tags">
                ${data.tags.map(tag => `<span class="profile-tag">${tag}</span>`).join('')}
            </div>
            <div class="profile-actions">
                <button class="action-btn contact-btn">
                    <i class="bi bi-chat-dots"></i>
                    联系咨询
                </button>
                <button class="action-btn follow-btn">
                    <i class="bi bi-heart"></i>
                    关注
                </button>
            </div>
        </section>

        <!-- 关于我 -->
        <section class="section-container">
            <h2 class="section-title"><i class="bi bi-person-vcard"></i> 关于我</h2>
            <p class="about-content">${data.about}</p>
            <div class="stats-grid">
                <div class="stat-card">
                    <div class="stat-value">${data.stats.students}</div>
                    <div class="stat-label">服务学员</div>
                </div>
                <div class="stat-card">
                    <div class="stat-value">${data.stats.satisfactionRate}</div>
                    <div class="stat-label">好评率</div>
                </div>
                <div class="stat-card">
                    <div class="stat-value">${data.stats.salaryIncrease}</div>
                    <div class="stat-label">平均提薪</div>
                </div>
            </div>
        </section>

        <!-- 服务内容 -->
        <section class="section-container">
            <h2 class="section-title"><i class="bi bi-grid"></i> 服务内容</h2>
            <div class="service-cards">
                ${data.services.map(service => `
                    <div class="service-card">
                        <h4>${service.name}</h4>
                        <p class="price">¥${service.price}</p>
                    </div>
                `).join('')}
            </div>
        </section>

        <!-- 个人经历 -->
        <section class="section-container">
            <h2 class="section-title"><i class="bi bi-briefcase"></i> 个人经历</h2>
            <div class="timeline">
                ${data.experience.map(exp => `
                    <div class="timeline-item">
                        <div class="timeline-dot"></div>
                        <div class="timeline-content">
                            <h3 class="timeline-title">${exp.title}</h3>
                            <p class="timeline-period">${exp.period}</p>
                            <p class="timeline-desc">${exp.position}：${exp.description}</p>
                        </div>
                    </div>
                `).join('')}
            </div>
        </section>

        <!-- 学员评价 -->
        <section class="section-container">
            <h2 class="section-title"><i class="bi bi-star"></i> 学员评价</h2>
            <div class="review-cards">
                ${data.reviews.map(review => `
                    <div class="review-card">
                        <div class="reviewer">
                            <img src="${review.avatar}" alt="${review.name}" class="reviewer-avatar">
                            <div class="reviewer-info">
                                <h3 class="reviewer-name">${review.name}</h3>
                                <p class="review-date">${review.date}</p>
                            </div>
                            <div class="reviewer-rating">
                                ${Array(review.rating).fill('<i class="bi bi-star-fill"></i>').join('')}
                                ${Array(5 - review.rating).fill('<i class="bi bi-star"></i>').join('')}
                            </div>
                        </div>
                        <p class="review-text">${review.content}</p>
                    </div>
                `).join('')}
            </div>
            <div class="view-more">
                <button class="view-more-btn">
                    查看更多评价
                    <i class="bi bi-chevron-down"></i>
                </button>
            </div>
        </section>
        
        <!-- 推荐经纪人 -->
        <section class="section-container">
            <h2 class="section-title">
                <span><i class="bi bi-award"></i> 推荐经纪人</span>
                <a href="recommend-agents.html" class="view-all-link">
                    查看全部
                    <i class="bi bi-arrow-right"></i>
                </a>
            </h2>
            <div class="recommended-agents">
                ${getRecommendedAgents(data.id).slice(0, 3).map(agent => `
                    <div class="recommended-agent-card" data-agent-id="${agent.id}">
                        <div class="agent-card-header">
                            <img src="${agent.avatar}" alt="${agent.name}" class="agent-card-avatar">
                            <div class="agent-card-info">
                                <h3 class="agent-card-name">${agent.name} ${agent.verified ? '<i class="bi bi-patch-check-fill"></i>' : ''}</h3>
                                <p class="agent-card-title">${agent.title}</p>
                                <div class="agent-card-rating">
                                    <span class="rating-stars">
                                        ${Array(Math.floor(agent.rating)).fill('<i class="bi bi-star-fill"></i>').join('')}
                                        ${agent.rating % 1 > 0 ? '<i class="bi bi-star-half"></i>' : ''}
                                    </span>
                                    <span class="rating-number">${agent.rating}</span>
                                </div>
                            </div>
                        </div>
                        <div class="agent-card-tags">
                            ${agent.tags.slice(0, 2).map(tag => `<span class="agent-card-tag">${tag}</span>`).join('')}
                        </div>
                    </div>
                `).join('')}
            </div>
        </section>
    `;
    
    // 添加内容到页面
    detailContainer.innerHTML = content;
    
    // 添加底部间距，防止内容被底部CTA遮挡
    const bottomSpacer = document.createElement('div');
    bottomSpacer.style.height = '80px';
    detailContainer.appendChild(bottomSpacer);
    
    // 初始化推荐经纪人卡片点击事件
    initRecommendedAgentCards();
}

// 获取推荐经纪人数据
function getRecommendedAgents(currentAgentId) {
    // 获取所有经纪人数据
    const agentsData = {
        'agent1': {
            id: 'agent1',
            name: '张明',
            title: '前BAT高级HR',
            avatar: 'https://images.pexels.com/photos/3760263/pexels-photo-3760263.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1',
            rating: 4.9,
            verified: true,
            tags: ['简历优化', '面试辅导', '互联网行业']
        },
        'agent2': {
            id: 'agent2',
            name: '王静',
            title: '资深金融顾问',
            avatar: 'https://images.pexels.com/photos/5393594/pexels-photo-5393594.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1',
            rating: 5.0,
            verified: true,
            tags: ['职业规划', '投行求职', '金融行业']
        },
        'agent3': {
            id: 'agent3',
            name: '李华',
            title: '金融行业导师',
            avatar: 'https://images.pexels.com/photos/3785104/pexels-photo-3785104.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1',
            rating: 4.8,
            verified: true,
            tags: ['职业规划', '求职策略', '金融行业']
        },
        'agent4': {
            id: 'agent4',
            name: '陈进',
            title: '互联网产品专家',
            avatar: 'https://images.pexels.com/photos/614810/pexels-photo-614810.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1',
            rating: 4.7,
            verified: true,
            tags: ['产品设计', 'PM求职', '互联网行业']
        },
        'agent5': {
            id: 'agent5',
            name: '刘芳',
            title: '教育行业顾问',
            avatar: 'https://images.pexels.com/photos/762020/pexels-photo-762020.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1',
            rating: 4.6,
            verified: false,
            tags: ['教师发展', '职业规划', '教育行业']
        }
    };
    
    // 排除当前经纪人
    const recommendations = Object.values(agentsData).filter(agent => agent.id !== currentAgentId);
    
    // 随机打乱顺序，模拟推荐算法
    return recommendations.sort(() => Math.random() - 0.5);
}

// 初始化推荐经纪人卡片点击事件
function initRecommendedAgentCards() {
    const agentCards = document.querySelectorAll('.recommended-agent-card');
    
    agentCards.forEach(card => {
        card.addEventListener('click', function() {
            const agentId = this.getAttribute('data-agent-id');
            if (agentId) {
                window.location.href = `agent-detail.html?id=${agentId}`;
            }
        });
    });
}

// 更新底部价格
function updatePrice(price) {
    const priceElement = document.getElementById('agent-price');
    if (priceElement) {
        priceElement.textContent = price;
    }
}

// 初始化页面交互
function initPageInteractions(data) {
    // 预约按钮点击事件
    const bookBtn = document.querySelector('.cta-btn');
    if (bookBtn) {
        bookBtn.addEventListener('click', function() {
            // 打开预约弹窗
            openBookingModal(data);
        });
    }
    
    // 联系咨询按钮
    const contactBtn = document.querySelector('.contact-btn');
    if (contactBtn) {
        contactBtn.addEventListener('click', function() {
            // 打开预约弹窗
            openBookingModal(data);
        });
    }
    
    // 关注按钮
    const followBtn = document.querySelector('.follow-btn');
    if (followBtn) {
        followBtn.addEventListener('click', function() {
            if (this.classList.contains('followed')) {
                this.classList.remove('followed');
                this.innerHTML = '<i class="bi bi-heart"></i> 关注';
                this.style.backgroundColor = '#f0f4ff';
                this.style.color = 'var(--primary-color)';
                showMessage(`您已取消关注 ${data.name}`);
            } else {
                this.classList.add('followed');
                this.innerHTML = '<i class="bi bi-heart-fill"></i> 已关注';
                this.style.backgroundColor = '#e0e8ff';
                this.style.color = 'var(--primary-color)';
                showMessage(`您已成功关注 ${data.name}`);
            }
        });
    }
    
    // 查看更多评价按钮
    const viewMoreBtn = document.querySelector('.view-more-btn');
    if (viewMoreBtn) {
        let loadedReviewsCount = 0; // 已加载评价计数
        const reviewsPerLoad = 2; // 每次加载的评价数量
        
        viewMoreBtn.addEventListener('click', function() {
            // 显示加载状态
            this.innerHTML = '<i class="bi bi-hourglass-split"></i> 加载中...';
            this.disabled = true;
            
            // 保存当前已加载的评价数量
            const currentReviewCards = document.querySelectorAll('.review-card').length;
            loadedReviewsCount = currentReviewCards;
            
            // 模拟加载更多评价数据
            setTimeout(() => {
                try {
                    // 模拟获取更多评价
                    const moreReviews = getMoreReviews(data.id, loadedReviewsCount, reviewsPerLoad);
                    
                    if (moreReviews && moreReviews.length > 0) {
                        // 渲染更多评价
                        const reviewCards = document.querySelector('.review-cards');
                        if (reviewCards) {
                            moreReviews.forEach(review => {
                                const reviewCard = document.createElement('div');
                                reviewCard.className = 'review-card';
                                reviewCard.innerHTML = `
                                    <div class="reviewer">
                                        <img src="${review.avatar}" alt="${review.name}" class="reviewer-avatar">
                                        <div class="reviewer-info">
                                            <h3 class="reviewer-name">${review.name}</h3>
                                            <p class="review-date">${review.date}</p>
                                        </div>
                                        <div class="reviewer-rating">
                                            ${Array(review.rating).fill('<i class="bi bi-star-fill"></i>').join('')}
                                            ${Array(5 - review.rating).fill('<i class="bi bi-star"></i>').join('')}
                                        </div>
                                    </div>
                                    <p class="review-text">${review.content}</p>
                                `;
                                reviewCards.appendChild(reviewCard);
                            });
                            
                            // 为新添加的评价卡片添加动画效果
                            const newCards = reviewCards.querySelectorAll(`.review-card:nth-last-child(-n+${moreReviews.length})`);
                            newCards.forEach(card => {
                                card.style.animation = 'fadeIn 0.5s ease-in-out';
                            });
                            
                            // 滚动到新加载的评价
                            setTimeout(() => {
                                const firstNewCard = reviewCards.querySelector(`.review-card:nth-last-child(${moreReviews.length})`);
                                if (firstNewCard) {
                                    firstNewCard.scrollIntoView({ behavior: 'smooth', block: 'center' });
                                }
                            }, 200);
                            
                            // 添加"查看全部"按钮
                            if (loadedReviewsCount + moreReviews.length >= 5 && !document.querySelector('.view-all-btn')) {
                                const viewAllBtn = document.createElement('button');
                                viewAllBtn.className = 'view-all-btn';
                                viewAllBtn.innerHTML = '查看全部评价 <i class="bi bi-arrow-right"></i>';
                                
                                // 为"查看全部"按钮添加点击事件
                                viewAllBtn.addEventListener('click', function() {
                                    // 跳转到评价详情页
                                    window.location.href = `agent-reviews.html?id=${data.id}&name=${encodeURIComponent(data.name)}`;
                                });
                                
                                // 将按钮添加到评价区域
                                const viewMoreContainer = document.querySelector('.view-more');
                                if (viewMoreContainer) {
                                    viewMoreContainer.appendChild(viewAllBtn);
                                }
                            }
                        } else {
                            console.error('找不到评价卡片容器');
                        }
                        
                        // 更新按钮状态
                        this.innerHTML = '查看更多评价 <i class="bi bi-chevron-down"></i>';
                        this.disabled = false;
                        
                        // 如果没有更多评价了，隐藏按钮
                        if (moreReviews.length < reviewsPerLoad) {
                            this.style.display = 'none';
                            // 添加"已显示全部评价"的提示
                            const reviewSection = document.querySelector('.view-more');
                            const allReviewsShown = document.createElement('p');
                            allReviewsShown.className = 'all-reviews-shown';
                            allReviewsShown.textContent = '已显示全部评价';
                            allReviewsShown.style.textAlign = 'center';
                            allReviewsShown.style.color = '#999';
                            allReviewsShown.style.fontSize = '12px';
                            allReviewsShown.style.margin = '10px 0';
                            reviewSection.appendChild(allReviewsShown);
                        }
                    } else {
                        // 没有更多评价了
                        this.style.display = 'none';
                        showMessage('已经显示全部评价');
                    }
                } catch (error) {
                    console.error('加载更多评价时出错:', error);
                    this.innerHTML = '查看更多评价 <i class="bi bi-chevron-down"></i>';
                    this.disabled = false;
                    showMessage('加载更多评价失败，请稍后再试');
                }
            }, 1000);
        });
    }
    
    // 添加"查看全部评价"按钮
    const reviewSection = document.querySelector('.section-container:last-of-type');
    if (reviewSection && data.reviewCount > 3) {
        const viewAllContainer = document.createElement('div');
        viewAllContainer.className = 'view-all-container';
        viewAllContainer.innerHTML = `
            <button class="view-all-btn">
                查看全部评价 <i class="bi bi-arrow-right"></i>
            </button>
        `;
        reviewSection.appendChild(viewAllContainer);
        
        // 为"查看全部"按钮添加点击事件
        const viewAllBtn = viewAllContainer.querySelector('.view-all-btn');
        viewAllBtn.addEventListener('click', function() {
            // 跳转到评价详情页
            window.location.href = `agent-reviews.html?id=${data.id}&name=${encodeURIComponent(data.name)}`;
        });
    }
    
    // 服务卡片点击事件
    const serviceCards = document.querySelectorAll('.service-card');
    serviceCards.forEach(card => {
        card.addEventListener('click', function() {
            const serviceName = this.querySelector('h4').textContent;
            const servicePrice = this.querySelector('.price').textContent;
            
            // 更新预约内容为选中的服务
            const userContent = document.getElementById('userContent');
            if (userContent) {
                userContent.value = `我想预约"${serviceName}"服务，${servicePrice}`;
            }
            
            // 找到最低价位的服务
            const minPriceService = data.services.reduce((min, service) => {
                return service.price < min.price ? service : min;
            }, data.services[0]);
            
            // 清除所有服务卡片的选中状态
            document.querySelectorAll('.service-card').forEach(sc => {
                sc.classList.remove('selected');
            });
            
            // 如果当前点击的不是最低价位的服务，选中最低价位
            // 否则选中当前点击的服务
            const allServiceCards = document.querySelectorAll('.service-card');
            allServiceCards.forEach(sc => {
                const cardName = sc.querySelector('h4').textContent;
                if (cardName === minPriceService.name) {
                    sc.classList.add('selected');
                }
            });
            
            // 打开预约弹窗
            openBookingModal(data);
        });
    });
    
    // 初始化预约弹窗交互
    initBookingModal();
}

// 打开预约弹窗
function openBookingModal(data) {
    const modal = document.getElementById('bookingModal');
    if (!modal) {
        // 如果HTML中没有预约弹窗结构，动态创建
        createBookingModal();
        initBookingModal();
    }
    
    // 设置经纪人信息
    document.getElementById('agentQrCodeName').textContent = `${data.name} · ${data.title}`;
    
    // 设置经纪人二维码（使用模拟数据）
    const qrCodeSrc = getAgentQrCode(data.id);
    document.getElementById('agentQrCode').src = qrCodeSrc;
    
    // 显示弹窗
    document.getElementById('bookingModal').classList.add('active');
    document.body.style.overflow = 'hidden'; // 防止背景滚动
}

// 初始化预约弹窗交互
function initBookingModal() {
    const modal = document.getElementById('bookingModal');
    if (!modal) return;
    
    // 关闭按钮点击事件
    const closeBtn = modal.querySelector('.close-btn');
    if (closeBtn) {
        closeBtn.addEventListener('click', closeBookingModal);
    }
    
    // 取消按钮点击事件
    const cancelBtn = modal.querySelector('.cancel-btn');
    if (cancelBtn) {
        cancelBtn.addEventListener('click', closeBookingModal);
    }
    
    // 提交按钮点击事件
    const submitBtn = modal.querySelector('.submit-btn');
    if (submitBtn) {
        submitBtn.addEventListener('click', submitBooking);
    }
    
    // 点击弹窗外部关闭弹窗
    modal.addEventListener('click', function(e) {
        if (e.target === modal) {
            closeBookingModal();
        }
    });
}

// 关闭预约弹窗
function closeBookingModal() {
    const modal = document.getElementById('bookingModal');
    if (modal) {
        modal.classList.remove('active');
        document.body.style.overflow = ''; // 恢复背景滚动
    }
}

// 提交预约信息
function submitBooking() {
    const userName = document.getElementById('userName').value.trim();
    const userPhone = document.getElementById('userPhone').value.trim();
    const userContent = document.getElementById('userContent').value.trim();
    
    // 表单验证
    if (!userName) {
        showMessage('请输入您的姓名');
        return;
    }
    
    if (!userPhone) {
        showMessage('请输入您的联系电话');
        return;
    }
    
    // 手机号格式验证
    if (!/^1[3-9]\d{9}$/.test(userPhone)) {
        showMessage('请输入正确的手机号码');
        return;
    }
    
    // 模拟提交
    // 在实际项目中，这里应该发送数据到服务器
    setTimeout(() => {
        showMessage('预约信息已提交成功！');
        
        // 清空表单
        document.getElementById('userName').value = '';
        document.getElementById('userPhone').value = '';
        document.getElementById('userContent').value = '';
        
        // 关闭弹窗
        closeBookingModal();
    }, 800);
}

// 获取经纪人二维码（模拟数据）
function getAgentQrCode(agentId) {
    // 模拟数据，在实际项目中应该从服务器获取经纪人的真实二维码
    const qrCodes = {
        'agent1': 'https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=http://weixin.qq.com/r/GpLXgZXEVSVArRlL925-',
        'agent2': 'https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=http://weixin.qq.com/r/Y8MoRW7EHc_FrVdz925T',
        'agent3': 'https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=http://weixin.qq.com/r/LpO9tZDESQVMrZ80928c'
    };
    
    return qrCodes[agentId] || 'https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=https://example.com';
}

// 动态创建预约弹窗
function createBookingModal() {
    const modalHtml = `
        <div class="booking-modal" id="bookingModal">
            <div class="modal-content">
                <div class="modal-header">
                    <h3>预约表单</h3>
                    <button class="close-btn"><i class="bi bi-x-lg"></i></button>
                </div>
                <div class="modal-body">
                    <div class="form-group">
                        <label for="userName">姓名</label>
                        <input type="text" id="userName" placeholder="请输入您的姓名" required>
                    </div>
                    <div class="form-group">
                        <label for="userPhone">电话</label>
                        <input type="tel" id="userPhone" placeholder="请输入您的联系电话" required>
                    </div>
                    <div class="form-group">
                        <label for="userContent">预约内容</label>
                        <textarea id="userContent" placeholder="请简要描述您需要咨询的内容" rows="3"></textarea>
                    </div>
                    <div class="qr-code-section">
                        <p>长按下方二维码添加经纪人企业微信</p>
                        <div class="qr-code-container">
                            <img id="agentQrCode" src="" alt="经纪人微信二维码">
                            <p id="agentQrCodeName"></p>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button class="cancel-btn">取消</button>
                    <button class="submit-btn">提交预约</button>
                </div>
            </div>
        </div>
    `;
    
    // 添加到页面
    const modalElement = document.createElement('div');
    modalElement.innerHTML = modalHtml;
    document.body.appendChild(modalElement.firstElementChild);
    
    // 添加样式
    const style = document.createElement('style');
    style.textContent = `
        /* 预约弹窗样式 */
        .booking-modal {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.6);
            z-index: 1000;
            display: none;
            align-items: center;
            justify-content: center;
            animation: fadeIn 0.3s ease;
        }
        
        .booking-modal.active {
            display: flex;
        }
        
        .modal-content {
            background-color: white;
            width: 90%;
            max-width: 360px;
            border-radius: 12px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.15);
            overflow: hidden;
            animation: slideUp 0.3s ease;
        }
        
        .modal-header {
            padding: 16px 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            border-bottom: 1px solid #f0f0f0;
        }
        
        .modal-header h3 {
            font-size: 18px;
            margin: 0;
            color: #333;
        }
        
        .close-btn {
            background: transparent;
            border: none;
            font-size: 18px;
            cursor: pointer;
            color: #999;
            display: flex;
            padding: 0;
        }
        
        .modal-body {
            padding: 20px;
        }
        
        .form-group {
            margin-bottom: 16px;
        }
        
        .form-group label {
            display: block;
            font-size: 14px;
            color: #666;
            margin-bottom: 6px;
        }
        
        .form-group input,
        .form-group textarea {
            width: 100%;
            padding: 12px 14px;
            border: 1px solid #e0e0e0;
            border-radius: 8px;
            font-size: 14px;
            transition: all 0.3s;
        }
        
        .form-group input:focus,
        .form-group textarea:focus {
            border-color: var(--primary-color);
            box-shadow: 0 0 0 3px rgba(78, 110, 242, 0.1);
            outline: none;
        }
        
        .qr-code-section {
            text-align: center;
            margin-top: 20px;
            padding-top: 20px;
            border-top: 1px dashed #e0e0e0;
        }
        
        .qr-code-section p {
            font-size: 14px;
            color: #666;
            margin-bottom: 16px;
        }
        
        .qr-code-container {
            display: inline-block;
            position: relative;
        }
        
        .qr-code-container img {
            width: 150px;
            height: 150px;
            border: 1px solid #f0f0f0;
            border-radius: 8px;
            padding: 5px;
        }
        
        .qr-code-container p {
            margin-top: 8px;
            font-size: 14px;
            font-weight: 500;
            color: #333;
        }
        
        .modal-footer {
            display: flex;
            padding: 16px 20px;
            border-top: 1px solid #f0f0f0;
            gap: 12px;
        }
        
        .cancel-btn, .submit-btn {
            flex: 1;
            height: 44px;
            border-radius: 8px;
            font-size: 15px;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.3s;
        }
        
        .cancel-btn {
            background-color: #f5f5f5;
            color: #666;
            border: none;
        }
        
        .submit-btn {
            background-color: var(--primary-color);
            color: white;
            border: none;
        }
        
        .cancel-btn:hover {
            background-color: #ebebeb;
        }
        
        .submit-btn:hover {
            background-color: var(--secondary-color);
        }
        
        @keyframes fadeIn {
            from { opacity: 0; }
            to { opacity: 1; }
        }
        
        @keyframes slideUp {
            from { transform: translateY(20px); opacity: 0.8; }
            to { transform: translateY(0); opacity: 1; }
        }
    `;
    
    document.head.appendChild(style);
}

// 初始化返回按钮
function initBackButton() {
    const backBtn = document.querySelector('.back-btn');
    if (backBtn) {
        backBtn.addEventListener('click', function(e) {
            e.preventDefault();
            window.history.back();
        });
    }
}

// 初始化分享按钮
function initShareButton() {
    const shareBtn = document.querySelector('.search-btn');
    if (shareBtn) {
        shareBtn.addEventListener('click', function() {
            if (navigator.share) {
                navigator.share({
                    title: document.title,
                    url: window.location.href
                }).then(() => {
                    console.log('分享成功');
                }).catch((error) => {
                    console.log('分享失败:', error);
                    showMessage('分享功能暂不可用');
                });
            } else {
                showMessage('浏览器不支持分享功能');
            }
        });
    }
}

// 显示错误信息
function showError(message) {
    const detailContainer = document.getElementById('agent-detail-content');
    detailContainer.innerHTML = `
        <div class="error-container">
            <i class="bi bi-exclamation-triangle"></i>
            <p>${message}</p>
            <button class="back-to-list">返回列表</button>
        </div>
    `;
    
    // 添加返回列表按钮事件
    const backBtn = document.querySelector('.back-to-list');
    if (backBtn) {
        backBtn.addEventListener('click', function() {
            window.location.href = 'agents.html';
        });
    }
}

// 显示消息提示
function showMessage(message) {
    // 创建消息元素
    const messageElement = document.createElement('div');
    messageElement.classList.add('toast-message');
    messageElement.textContent = message;
    
    // 添加样式
    messageElement.style.position = 'fixed';
    messageElement.style.bottom = '80px';
    messageElement.style.left = '50%';
    messageElement.style.transform = 'translateX(-50%)';
    messageElement.style.backgroundColor = 'rgba(0, 0, 0, 0.7)';
    messageElement.style.color = 'white';
    messageElement.style.padding = '10px 20px';
    messageElement.style.borderRadius = '20px';
    messageElement.style.fontSize = '14px';
    messageElement.style.zIndex = '1000';
    messageElement.style.transition = 'opacity 0.3s';
    
    // 添加到页面
    document.body.appendChild(messageElement);
    
    // 3秒后移除
    setTimeout(() => {
        messageElement.style.opacity = '0';
        setTimeout(() => {
            document.body.removeChild(messageElement);
        }, 300);
    }, 2000);
}

// 修改底部CTA样式，使其符合app风格
function updateBottomCTAStyle() {
    const bottomCta = document.querySelector('.bottom-cta');
    if (bottomCta) {
        // 获取设备宽度，根据设备宽度调整样式
        const deviceWidth = window.innerWidth;
        const isSmallDevice = deviceWidth < 375;
        const isMediumDevice = deviceWidth >= 375 && deviceWidth < 500;
        const isLargeDevice = deviceWidth >= 500;
        
        // 计算适合当前屏幕的高度和内边距
        let ctaHeight = isSmallDevice ? '60px' : (isMediumDevice ? '65px' : '70px');
        let ctaPadding = isSmallDevice ? '10px 12px' : (isMediumDevice ? '12px 16px' : '14px 20px');
        
        // 修改底部CTA容器样式
        bottomCta.style.padding = ctaPadding;
        bottomCta.style.height = ctaHeight;
        bottomCta.style.borderTop = '1px solid #f0f0f0';
        bottomCta.style.width = '100%';
        bottomCta.style.maxWidth = '100%';
        bottomCta.style.boxSizing = 'border-box';
        bottomCta.style.boxShadow = '0 -4px 12px rgba(0, 0, 0, 0.08)';
        
        try {
            bottomCta.style.backdropFilter = 'blur(10px)';
            bottomCta.style.webkitBackdropFilter = 'blur(10px)';
            bottomCta.style.backgroundColor = 'rgba(255, 255, 255, 0.95)';
        } catch (e) {
            console.log('不支持backdrop-filter属性', e);
            bottomCta.style.backgroundColor = 'white';
        }
        
        // 确保CTA与app容器宽度保持一致
        const appContainer = document.querySelector('.app-container');
        if (appContainer) {
            const appWidth = appContainer.offsetWidth;
            bottomCta.style.maxWidth = appWidth + 'px';
            bottomCta.style.left = '50%';
            bottomCta.style.transform = 'translateX(-50%)';
        }
        
        // 修改价格区域样式
        const ctaPrice = document.querySelector('.cta-price');
        if (ctaPrice) {
            ctaPrice.style.paddingLeft = isSmallDevice ? '2px' : '4px';
        }
        
        // 修改价格标签样式
        const priceLabel = document.querySelector('.price-label');
        if (priceLabel) {
            priceLabel.style.fontSize = isSmallDevice ? '10px' : '12px';
            priceLabel.style.marginBottom = '0';
        }
        
        // 修改价格值样式
        const priceValue = document.querySelector('.price-value');
        if (priceValue) {
            priceValue.style.fontSize = isSmallDevice ? '18px' : (isMediumDevice ? '20px' : '22px');
            
            // 设置¥符号样式
            const priceChildren = priceValue.childNodes;
            if (priceChildren.length > 0 && priceChildren[0].nodeType === Node.TEXT_NODE && priceChildren[0].textContent.includes('¥')) {
                // 如果价格前面已经有¥符号，调整其大小
                priceValue.style.display = 'flex';
                priceValue.style.alignItems = 'center';
                
                // 创建一个新的元素来替换文本节点中的¥符号
                const priceText = priceChildren[0].textContent;
                if (priceText.includes('¥')) {
                    const yuanSymbol = document.createElement('span');
                    yuanSymbol.textContent = '¥';
                    yuanSymbol.style.fontSize = isSmallDevice ? '14px' : '16px';
                    yuanSymbol.style.marginRight = '1px';
                    yuanSymbol.style.position = 'relative';
                    yuanSymbol.style.top = '-1px';
                    
                    // 替换原有文本节点
                    const newText = document.createTextNode(priceText.replace('¥', ''));
                    priceValue.insertBefore(yuanSymbol, priceChildren[0]);
                    priceValue.replaceChild(newText, priceChildren[0]);
                }
            }
        }
        
        // 修改按钮样式
        const ctaBtn = document.querySelector('.cta-btn');
        if (ctaBtn) {
            // 根据设备尺寸计算按钮尺寸
            const btnPadding = isSmallDevice ? '10px 16px' : (isMediumDevice ? '12px 22px' : '14px 28px');
            const btnFontSize = isSmallDevice ? '14px' : (isMediumDevice ? '15px' : '16px');
            const btnMaxWidth = isSmallDevice ? '130px' : (isMediumDevice ? '145px' : '160px');
            
            ctaBtn.style.borderRadius = isSmallDevice ? '22px' : '28px';
            ctaBtn.style.padding = btnPadding;
            ctaBtn.style.fontSize = btnFontSize;
            ctaBtn.style.maxWidth = btnMaxWidth;
            ctaBtn.style.letterSpacing = '0.5px';
            ctaBtn.style.boxShadow = '0 4px 12px rgba(78, 110, 242, 0.25)';
            ctaBtn.style.background = 'linear-gradient(135deg, var(--primary-color), var(--secondary-color))';
            ctaBtn.style.position = 'relative';
            ctaBtn.style.overflow = 'hidden';
            ctaBtn.style.transition = 'all 0.3s ease';
            
            // 添加鼠标悬停和点击效果
            ctaBtn.addEventListener('mouseover', function() {
                this.style.transform = 'translateY(-2px)';
                this.style.boxShadow = '0 6px 16px rgba(78, 110, 242, 0.35)';
            });
            
            ctaBtn.addEventListener('mouseout', function() {
                this.style.transform = '';
                this.style.boxShadow = '0 4px 12px rgba(78, 110, 242, 0.25)';
            });
            
            ctaBtn.addEventListener('mousedown', function() {
                this.style.transform = 'translateY(0)';
                this.style.boxShadow = '0 2px 8px rgba(78, 110, 242, 0.2)';
            });
            
            ctaBtn.addEventListener('mouseup', function() {
                this.style.transform = 'translateY(-2px)';
                this.style.boxShadow = '0 6px 16px rgba(78, 110, 242, 0.35)';
            });
            
            // 添加闪光效果（只有在大屏设备上才添加，减少小屏设备的性能负担）
            if (isLargeDevice && !document.querySelector('.cta-btn span')) {
                const shine = document.createElement('span');
                shine.style.position = 'absolute';
                shine.style.top = '0';
                shine.style.left = '0';
                shine.style.width = '100%';
                shine.style.height = '100%';
                shine.style.background = 'linear-gradient(90deg, rgba(255,255,255,0) 0%, rgba(255,255,255,0.2) 50%, rgba(255,255,255,0) 100%)';
                shine.style.transform = 'translateX(-100%)';
                shine.style.pointerEvents = 'none';
                ctaBtn.appendChild(shine);
                
                // 添加动画效果
                setTimeout(() => {
                    shine.style.transition = 'transform 1s ease-in-out';
                    shine.style.transform = 'translateX(100%)';
                    
                    setInterval(() => {
                        shine.style.transition = 'none';
                        shine.style.transform = 'translateX(-100%)';
                        
                        setTimeout(() => {
                            shine.style.transition = 'transform 1s ease-in-out';
                            shine.style.transform = 'translateX(100%)';
                        }, 50);
                    }, 5000);
                }, 1000);
            }
        }
        
        // 调整底部间距，确保内容不被底部栏遮挡
        const bottomSpacer = document.querySelector('#agent-detail-content > div:last-child');
        if (bottomSpacer && bottomSpacer.tagName !== 'SECTION') {
            bottomSpacer.style.height = parseInt(ctaHeight, 10) + 10 + 'px';
        } else {
            const newSpacer = document.createElement('div');
            newSpacer.style.height = parseInt(ctaHeight, 10) + 10 + 'px';
            document.getElementById('agent-detail-content').appendChild(newSpacer);
        }
    }
}

// 选择最低价位的服务
function selectMinPriceService(data) {
    setTimeout(() => {
        // 找到最低价位的服务
        const minPriceService = data.services.reduce((min, service) => {
            return service.price < min.price ? service : min;
        }, data.services[0]);
        
        // 查找所有服务卡片
        const serviceCards = document.querySelectorAll('.service-card');
        
        // 选中最低价位的服务卡片
        serviceCards.forEach(card => {
            const cardName = card.querySelector('h4').textContent;
            if (cardName === minPriceService.name) {
                card.classList.add('selected');
            }
        });
    }, 100); // 短暂延时确保DOM已完全渲染
}

// 获取更多评价（模拟数据）
function getMoreReviews(agentId, skip, limit) {
    // 额外的模拟评价数据
    const extraReviews = {
        'agent1': [
            {
                name: '郑同学',
                avatar: 'https://images.pexels.com/photos/1438072/pexels-photo-1438072.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1',
                rating: 5,
                date: '2022-12-20',
                content: '张老师的简历指导非常专业，帮我发现了很多简历中的亮点和不足，修改后投递成功率提高了很多！'
            },
            {
                name: '黄同学',
                avatar: 'https://images.pexels.com/photos/2531553/pexels-photo-2531553.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1',
                rating: 4,
                date: '2022-11-15',
                content: '面试辅导课非常有帮助，张老师给了我很多针对性的建议，最终成功通过了几家大厂的面试。'
            },
            {
                name: '马同学',
                avatar: 'https://images.pexels.com/photos/91227/pexels-photo-91227.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1',
                rating: 5,
                date: '2022-10-08',
                content: '全程跟踪服务非常贴心，从简历修改到面试准备再到offer选择，每一步都得到了专业指导，最后拿到了满意的offer！'
            }
        ],
        'agent2': [
            {
                name: '钱同学',
                avatar: 'https://images.pexels.com/photos/774909/pexels-photo-774909.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1',
                rating: 5,
                date: '2022-12-05',
                content: '王老师的金融行业分析非常深入，帮我理清了不同细分领域的特点和要求，最终找到了最适合自己的方向。'
            },
            {
                name: '孙同学',
                avatar: 'https://images.pexels.com/photos/220453/pexels-photo-220453.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1',
                rating: 4,
                date: '2022-11-10',
                content: '案例分析课程给了我很多实用的方法和思路，对后续面试有很大帮助，推荐给想进入金融行业的同学！'
            }
        ],
        'agent3': [
            {
                name: '赵同学',
                avatar: 'https://images.pexels.com/photos/2379005/pexels-photo-2379005.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1',
                rating: 5,
                date: '2023-03-10',
                content: '李老师的职业规划课程让我对金融行业有了更清晰的认识，找到了适合自己的发展方向。简历修改也非常专业，投递成功率大大提高。'
            },
            {
                name: '孙同学',
                avatar: 'https://images.pexels.com/photos/1516680/pexels-photo-1516680.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1',
                rating: 4,
                date: '2023-01-25',
                content: '求职辅导很有针对性，李老师分享了很多行业内部的见解和面试技巧。唯一的建议是希望能增加更多实践性的内容，但总体来说非常满意。'
            },
            {
                name: '徐同学',
                avatar: 'https://images.pexels.com/photos/614810/pexels-photo-614810.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1',
                rating: 5,
                date: '2022-12-12',
                content: '简历优化服务非常专业，李老师帮我重新组织了项目经验和技能展示，面试邀约数量明显增加，非常感谢！'
            }
        ]
    };
    
    // 检查是否有更多评价
    if (!extraReviews[agentId] || skip >= extraReviews[agentId].length) {
        return [];
    }
    
    // 返回指定数量的评价
    return extraReviews[agentId].slice(skip - 3, skip - 3 + limit);
} 